/**
 * 
 */
package com.ideal.trsdata.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ideal.trsdata.dao.ITrsDataDao;
import com.ideal.trsdata.model.BusiModel;
import com.ideal.trsdata.model.GpsInfoModel;
import com.ideal.trsdata.model.ProductModel;
import com.ideal.trsdata.model.TrsDataWarn;
import com.ideal.trsdata.model.TrsModel;
import com.ideal.trsdata.util.TrsDataConfig;
/**
 * 
 * <p>
 * Title: TrsDataImportService.java
 * </p>
 * <p>
 * Description: 
 * </p>
 * @author zhang_zhi
 * @version 1.0
 * @created Jul 20, 2011
 */
@Service
@Transactional
public class TrsDataImportService {
	@Autowired
	ITrsDataDao trsDataDao;
	@Autowired
	TrsPropertyService trsProService;
	private static final Log logger = LogFactory.getLog(TrsDataImportService.class);
	

	//主方法
	public void importTrs(TrsModel cus) throws Exception{
			this.getCustomer(cus);
			if(cus.getCustomer_id()==null)
				return;
			
			if(TrsDataConfig.addStatus.equals(cus.getStatus())||TrsDataConfig.updateStatus.equals(cus.getStatus())){
				this.delTrs(cus);  			//删除trs表中关于该商家的信息
				this.dealCustomer(cus);  	//处理该商家trs信息
				TrsDataConfig.log.debug("提取商家信息");
				this.dealLocalBusi(cus);    //处理该商家业务信息
				TrsDataConfig.log.debug("提取业务信息");
				this.insertFlow(cus);		//插入flow
			}else if(TrsDataConfig.delStatus.equals(cus.getStatus())){
				this.delTrs(cus);			//删除trs表中关于该商家的信息
				this.insertFlow(cus);		//插入flow
				this.insertDataLog(cus,this.getWarn("2",null,"0")); //记录日志
				TrsDataConfig.log.debug("删除trs信息");
			}else{
				TrsDataConfig.log.debug("serialid为"+cus.getSerialid()+"的deal_Status为不合法的处理方式");
				throw new Exception("serialid为"+cus.getSerialid()+"的deal_Status为不合法的处理方式");
			}
		
	}
	

	//商家信息提取
	public void getCustomer(TrsModel cus)throws Exception{
		if(cus.getProvCode()==null||cus.getSerialid()==null)
			throw new Exception("区划或者serialid不能置为空");
		String partition=("part"+cus.getProvCode().substring(0,2));
		cus.setPartition(partition);
		TrsModel c=trsDataDao.getCustomer(cus);
		if(c==null)
			throw new Exception("serialid为"+cus.getSerialid()+"的商家信息不存在");
		
		// 存在的设置属性
		cus.setComid(c.getComid());
		cus.setSerialid(c.getSerialid());
		cus.setProvCode(c.getProvCode());
		cus.setCityCode(c.getCityCode());
		cus.setSubCode(c.getSubCode());
		
		//加入regionCode处理
		if(c.getSubCode()!=null)
			cus.setRegionCode(c.getSubCode());
		else if(c.getSubCode()==null&&c.getCityCode()!=null)
			cus.setRegionCode(c.getCityCode());
		else
			cus.setRegionCode(c.getProvCode());
		cus.setCustomer_name(c.getCustomer_name());
		cus.setIndustry_name(c.getIndustry_name());
		cus.setEnglishName(c.getEnglishName());
		cus.setCustomer_id(c.getCustomer_id());
		//政企名称处理
		String aliasName = c.getAliasName();
		String codeName = c.getCodeName();
		String shortName = c.getShortName();
		String usedName = c.getUsedName();
		aliasName = codeName + "||" + shortName + "||" + aliasName + "||" + usedName;
		cus.setAliasName(aliasName);
		cus.setAddress(c.getAddress());
		cus.setTel(c.getTel());
		cus.setParentCustID(c.getParentCustID());
		cus.setIsopen(c.getIsopen());
		cus.setStatus(c.getStatus());
		cus.setCustCode(c.getCustCode());
		cus.setOrgShortPinyin(c.getOrgShortPinyin());
		cus.setTradeName(c.getTradeName());
	}
	
	//商家信息具体处理
	public void dealCustomer(TrsModel cus)throws Exception{
		cus.setRealAddress(cus.getAddress());
		cus.setRealCustomerName(cus.getCustomer_name());
		this.getTel(cus);
		//this.dealTel(cus);
		//j_organize中的电话号码。
		cus.setRealTel(cus.getTel());
		cus.setUniid(cus.getCustomer_id());
		cus.setGrade(trsDataDao.getGrade(cus));    //客户级别处理
		if(Integer.parseInt(cus.getGrade())>1){
			cus.setParentCustID(trsDataDao.getParentId(cus));
		}
		
		int i=Integer.parseInt(cus.getGrade());
		cus.setAdd(String.valueOf(i));
		
		//是否有下级部门处理
		String down=trsDataDao.getHasDept(cus);
		// 1-有下级部门 0-没有下级部门
		cus.setHasDept(down);
		
		//处理省+城市+区
		if(cus.getCityCode()==null)
			cus.setCityCode("");
		if(cus.getSubCode()==null)
			cus.setSubCode("");
		
		List<String> regionNameCity=trsDataDao.getRe("'".concat(cus.getProvCode()).concat("','").concat(cus.getCityCode()).concat("','").concat(cus.getSubCode().concat("'")));
		for(String region:regionNameCity){
			if(cus.getProvinceAndCity()==null||"".equals(cus.getProvinceAndCity()))
				cus.setProvinceAndCity(region);
			else
				cus.setProvinceAndCity(cus.getProvinceAndCity().concat(";").concat(region));
			
		}
		
		cus.setType(TrsDataConfig.ORGTYPE);		//客户类型设置

		this.dealCusCode(cus);					//客户编码设置 cus_code 为pinyingcode|addresscode
		cus.setIntroduction(trsDataDao.getDesc(cus));		//客户描述
		cus.setRealIntroduction(cus.getIntroduction());
		
		if(cus.getIndustry_name()!=null){
			String industry="'"+cus.getIndustry_name().replaceAll(";","','")+"'";
		
			//处理industryid
			List<String> industryid=trsDataDao.getSt(industry); //待定: industry id
		
			if(industryid!=null&&industryid.size()>0){
				for(String id:industryid){
					if(cus.getIndustry_id()==null||"".equals(cus.getIndustry_id())){
						cus.setIndustry_id(id);
						break;
					}
					cus.setIndustry_id(cus.getIndustry_id().concat(";").concat(id));
				}
			}
		}
		
		//设置政企集团业务及XY坐标
		cus = dealBusiness(cus);
	}
	
	public TrsModel dealBusiness(TrsModel cus)throws Exception{
		//获取订餐业务
		Integer isDc = trsDataDao.getFoodBusinessInfo(cus);
		cus.setIsDc(isDc);
		cus.setRealIsDc(isDc);
		//获取订房业务
		Integer isDf = trsDataDao.getHouseBusinessInfo(cus);
		cus.setIsDf(isDf);
		cus.setRealIsDf(isDf);
		//获取百事通加盟业务
		Integer isBst = trsDataDao.getBstBusinessInfo(cus);
		cus.setIsBst(isBst);
		cus.setRealIsBst(isBst);
		//获取优惠券业务
		Integer isYhq = trsDataDao.getCouponBusinessInfo(cus);
		cus.setIsYhq(isYhq);
		cus.setRealIsYhq(isYhq);
		//获取TRS业务
		Integer isTrs = trsDataDao.getTRSBusinessInfo(cus);
		cus.setIsTrs(isTrs);
		cus.setRealIsTrs(isTrs);
		//获取经纬度
		GpsInfoModel gpsInfo = trsDataDao.getGpsInfo(cus);
		if(gpsInfo!=null) {
			cus.setGpsx(gpsInfo.getGpsx());
			cus.setGpsy(gpsInfo.getGpsy());
			cus.setRealGpsx(gpsInfo.getGpsx());
			cus.setRealGpsy(gpsInfo.getGpsy());
		}
		return cus;
	}
	
	//获取经纬度
	public GpsInfoModel getGpsInfo(TrsModel cus)throws Exception{
		GpsInfoModel gpsInfo = new GpsInfoModel();
		gpsInfo = trsDataDao.getGpsInfo(cus);
		return gpsInfo;
	}
	
	//产品处理
	public void dealProduct(TrsModel cus)throws Exception{
		
		List<ProductModel> trs=new ArrayList<ProductModel>();
		List<ProductModel> cp=trsDataDao.getCustomerProduct(cus);	
		if(cp==null||cp.size()==0){
			//部门暂时不处理
			//this.dealDept(cus);
			cus.setCustomer_name(cus.getRealCustomerName());
			cus.setDeptId("0");
			cus.setUniid(cus.getCustomer_id());
			this.insertTrsWarn(cus);
			return;
		}
		
		for(ProductModel m:cp){
			if(cus.getProductspaceid()==null||"".equals(cus.getProductspaceid()))
				cus.setProductspaceid(m.getProduct_specid());
			else
				cus.setProductspaceid(cus.getProductspaceid().concat(";").concat(m.getProduct_specid()));
			
			
			//优先报号|品牌查询|实名查询|临时报号
			if(TrsDataConfig.ORGFLAG.indexOf(m.getProductName())>-1){
				trs.add(m);
			}
		}

		if(trs!=null&&trs.size()>0){
			//部门暂不处理
			//this.dealDept(cus);
			cus.setCustomer_name(cus.getRealCustomerName());
			cus.setDeptId("0");
			this.dealRecomProduct(trs,cus);
		}else{
			//部门暂不处理
			//this.dealDept(cus);
			cus.setCustomer_name(cus.getRealCustomerName());
			cus.setDeptId("0");
			cus.setUniid(cus.getCustomer_id());
			this.insertTrsWarn(cus);
		}
	}
	
	
	//产品销售单元及部分属性值处理
	public void dealRecomProduct(List<ProductModel> trs,TrsModel cus) throws Exception{
		ProductModel productM=null;
		boolean realNameFlag=true;
		
		
		
		for(ProductModel t:trs){

			if(cus.getIntroduction()==null)
				cus.setIntroduction("");
			boolean codeflag=true;
			cus.setContractid(t.getConnid());
			cus.setProductid(t.getProductid());
			cus.setProductBdpid(t.getId());
			cus.setUniid(cus.getCustomer_id()+"-0-"+t.getId());
			cus.setOffid(t.getOffid());
			String fieldName="'".concat(TrsDataConfig.RECOMMENDSPEC).
			concat("','").concat(TrsDataConfig.RANK_STRATEGY).concat("','").concat(TrsDataConfig.RANK_POSITION).
			concat("','").concat(TrsDataConfig.BALANCE_VALUE).concat("',").concat(TrsDataConfig.REALString).concat(",").concat(TrsDataConfig.TEMPString);
			List<ProductModel> ll=trsProService.findPropertyList(fieldName,TrsDataConfig.PropertyTable,cus.getProductBdpid());
			for(ProductModel p:ll){
				p.setProv(cus.getProvCode().substring(0, 2));
				if(TrsDataConfig.RECOMMENDSPEC.equals(p.getAttributeName())){
						productM=trsDataDao.getRecommend2(p);
						if(productM!=null)
							cus.setRecommid(productM.getAttributeValue());
						
						cus.setRecommendSubGroup(TrsDataConfig.RECOMMEND_SUB_GROUP);
				}
				
				if(TrsDataConfig.RANK_STRATEGY.equals(p.getAttributeName())&&p.getAttributeValue()!=null)
					cus.setRankStrategy(Integer.parseInt(p.getAttributeValue()));
				
				if(TrsDataConfig.RANK_POSITION.equals(p.getAttributeName())&&p.getAttributeValue()!=null)
					cus.setRankPosition(Integer.parseInt(p.getAttributeValue()));
				
				if(TrsDataConfig.BALANCE_VALUE.equals(p.getAttributeName()))
					cus.setBalanceValue(p.getAttributeValue());
				
				if(p.getAttributeName()!=null&&TrsDataConfig.REALNAMEFLAG.indexOf(p.getAttributeName())>-1){  //实名查询
					if(realNameFlag&&p.getAttributeValue()!=null&&!"".equals(p.getAttributeValue())){
						cus.setCustomer_name(cus.getRealCustomerName().concat("(").concat(p.getAttributeValue()).concat(")"));
						realNameFlag=false;
					}
					cus.setIntroduction(cus.getIntroduction().concat("※").concat(p.getAttributeValue()));	
				}else if(p.getAttributeName()!=null&&TrsDataConfig.REALCODEFLAG.indexOf(p.getAttributeName())>-1){ //实名查询编码
					cus.setIntroduction(cus.getIntroduction().concat("※").concat(p.getAttributeValue()));
				}
				
				if(p.getAttributeName()!=null&&TrsDataConfig.TEMPNAMEFLAG.indexOf(p.getAttributeName())>-1){ //临时报号
					if(realNameFlag&&codeflag&&p.getAttributeValue()!=null&&!"".equals(p.getAttributeValue())){
						cus.setCustomer_name(cus.getCustomer_name().concat("(").concat(p.getAttributeValue()).concat(")"));
						codeflag=false;
					}
						cus.setIntroduction(cus.getIntroduction().concat("※").concat(p.getAttributeValue()));
				} else if(p.getAttributeName()!=null&&TrsDataConfig.TEMPCODEFLAG.indexOf(p.getAttributeName())>-1){  //临时报号编码
					cus.setIntroduction(cus.getIntroduction().concat("※").concat(p.getAttributeValue()));
				}
			}
			if(productM==null)
				productM=new ProductModel();
		
			cus.setRecommendIndustry(productM.getIndustryName());
			cus.setRecommendKeyword(productM.getKeyWord());
				
			if(productM.getIndustryName()==null)
				cus.setIndustry_keyword(productM.getKeyWord());
			else if(productM.getIndustryName()!=null&&productM.getKeyWord()!=null)
				cus.setIndustry_keyword(productM.getIndustryName().concat(";").concat(productM.getKeyWord()));
			else if(productM.getKeyWord()==null&&productM.getIndustryName()!=null)
				cus.setIndustry_keyword(productM.getIndustryName());
			
			if(cus.getIndustry_keyword()==null)
				cus.setIndustry_keyword("");
			
			//将code加到后面
			if(productM.getKeyWordCode()!=null)
				cus.setIndustry_keyword(cus.getIndustry_keyword()+";"+productM.getKeyWordCode());
			
				
			cus.setRecCode(productM.getKeyWordCode());
			cus.setRecommendGroup(productM.getRecomId());			
			cus.setStartTime(productM.getStartTime());
			cus.setEndTime(productM.getEndTime());
			
			cus.setArea(trsDataDao.getRegionName(productM.getRegionName()));
			
			this.insertTrsWarn(cus);
			cus.setRecommid(null);
			cus.setRankStrategy(null);
			cus.setRankPosition(null);
			cus.setBalanceValue(null);
			cus.setCustomer_name(cus.getRealCustomerName());
			cus.setIntroduction(cus.getRealIntroduction());
		}
	
	}
	
	//省内业务处理
	public void dealLocalBusi(TrsModel cus)throws Exception{
		//List<BusiModel> trs = trsDataDao.getBusiInfo(cus);
		List<BusiModel> trs = new ArrayList<BusiModel>();
		if(trs!=null&&trs.size()>0){
			//部门暂不处理
			//this.dealDept(cus);
			cus.setCustomer_name(cus.getRealCustomerName());
			cus.setDeptId("0");
			
			//循环插入业务信息
			for (BusiModel busi : trs) {
				if(cus.getIntroduction()==null)
					cus.setIntroduction("");
				//产品ID
				if(cus.getProductspaceid()==null||"".equals(cus.getProductspaceid())) {
					cus.setProductspaceid(busi.getProductId());
				} else {
					cus.setProductspaceid(cus.getProductspaceid().concat(";").concat(busi.getProductId()));
				}
					
				//业务属性
				if(cus.getRecommendKeyword()==null||"".equals(cus.getRecommendKeyword())) {
					cus.setRecommendKeyword(busi.getBusiProperty());
				} else {
					cus.setRecommendKeyword(cus.getRecommendKeyword().concat(";").concat(busi.getBusiProperty()));
				}
				
				//备注
				if(cus.getCusMemo()==null||"".equals(cus.getCusMemo())) {
					cus.setCusMemo(busi.getBusiNote());
				} else {
					cus.setCusMemo(cus.getCusMemo().concat(";").concat(busi.getBusiNote()));
				}
				
				//权重
				if(cus.getRankPosition()==null||cus.getRankPosition()==0) {
					cus.setRankPosition(busi.getWeight());
				} else {
					cus.setRankPosition(cus.getRankPosition() + busi.getWeight());
				}
				
				//电话ID
				cus.setTelId(busi.getTelId());
				
			}
			
			//插入TRS
			this.insertTrsWarn(cus);
		}else{
			//部门暂不处理
			//this.dealDept(cus);
			cus.setCustomer_name(cus.getRealCustomerName());
			cus.setDeptId("0");
			cus.setUniid(cus.getCustomer_id());
			this.insertTrsWarn(cus);
		}
	}
	
	
	//得到宽表
	public List<TrsModel> getTrsTmp(Map map){
		List<TrsModel> trs=null;
			try {
				trs=trsDataDao.getTmp(map);
				trsDataDao.updateTmpTrsFlag(map);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return trs;
	}
	
	public List<TrsModel> getTrsTmpPorv(Map map){
		List<TrsModel> trs=null;
		try {
			trs=trsDataDao.getTmpProv(map);
			trsDataDao.updateTmpTrsFlag(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return trs;
	}
	
	//得到宽表:单条记录
	public TrsModel getSigTmp()throws Exception{
		TrsModel trs = trsDataDao.getSigTmp();
		if(trs!=null) {
			trsDataDao.updateSigTmpFlag(trs.getTrs_id());
		}
		return trs;
	}
	
	//得到宽表:50条记录
	public List<TrsModel> getTrsTmp(){
		List<TrsModel> trs=null;
		try {
			trs=trsDataDao.getTmp2();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return trs;
	}
	
	//插入trs
	public void insertTrs(TrsModel trs)throws Exception{
		trsDataDao.insertTrs(trs);
	}
	
	public TrsDataWarn getWarn(String updateMethod,String logMessage,String oper_log){
		TrsDataWarn warn=new TrsDataWarn();
		warn.setUpdate_method(updateMethod);
		warn.setLog_message(logMessage);
		warn.setOper_flag(oper_log);
		return warn;
	}
	
	//插入记录日志
	public void insertDataLog(TrsModel trs,TrsDataWarn trswarn) {
		if(trs!=null){
			trswarn.setContractid(trs.getContractid());
			trswarn.setOffid(trs.getOffid());
			trswarn.setProv_region_code(trs.getProvCode());
			trswarn.setOrgid(trs.getCustomer_id());
			trswarn.setProductid(trs.getProductBdpid());
		}
		trswarn.setPlant_name("全国三统一");
		trswarn.setModel_name("全国三统一输出");
		try {
			trsDataDao.insertWarn(trswarn);
			TrsDataConfig.log.debug("插入日志");
		} catch (Exception e) {
			TrsDataConfig.log.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	//插入flow 
	public void insertFlow(TrsModel trs)throws Exception{
		trs.setPlant_code(TrsDataConfig.PLANT_CODE);
		trs.setCreate_emplid(TrsDataConfig.CREATE_EMPLID);
		trsDataDao.insertFlow(trs);
		TrsDataConfig.log.debug("插入flow");
	}
	
	//更新接口表
	public void updateTmpTrs(TrsModel trs){
		try {
			trsDataDao.updateTmpTrs(trs);
			TrsDataConfig.log.debug("更新流水表信息");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//更新接口表
	public void updateTmpTrsFlag(Map map){
		try {
			trsDataDao.updateTmpTrsFlag(map);
			TrsDataConfig.log.debug("更新流水表标志位信息");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//更新接口表中未同步数据标志位
	public void updateTmpTrsErr(Map map){
		try {
			trsDataDao.updateTmpTrsErr(map);
			TrsDataConfig.log.debug("更新接口表中未同步数据标志位");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	//删除
	public void delTrs(TrsModel trs) throws Exception{
		trsDataDao.deleteTrs(trs);
	}
	
	//插入一条
	public void insertTrsWarn(TrsModel trs)throws Exception{
		this.insertTrs(trs);
		this.insertDataLog(trs,this.getWarn("1",null,"0"));
		TrsDataConfig.log.debug("记录插入trs宽表");
	}
	
	//初始化提取信息
	public TrsModel getCus() throws Exception{
		return trsDataDao.getCus(TrsDataConfig.atomicInt.getAndIncrement());
	}
	
	//提出初始信息 集合
	public List<TrsModel> getListCus(Map map)throws Exception{
		return trsDataDao.getListCus(map);
	}
	
	//提取政企电话
	public void getTel(TrsModel cus)throws Exception{
		List<TrsModel> tel=trsDataDao.getTel(cus);
		String telx="";
		if(tel!=null&&tel.size()>0){
			if(tel.size()>=50)
				tel=tel.subList(0, 50);
			for(TrsModel te:tel){
				if("1".equals(te.getStatus())||TrsDataConfig.TEL_SECRET_FLAG.equals(te.getStatus())){
					telx=telx+"*"+te.getTel()+" ";
				}else
					telx=telx+te.getTel()+" ";
			}
			if(telx.length()>500)
				telx.substring(0,500);
			
			cus.setTel(telx);
			cus.setRealTel(telx);
		}
	}
	
	//电话处理
	public void dealTel(TrsModel cus)throws Exception{
		//电话处理
		if(cus.getTel()!=null&&!"".equals(cus.getTel())){
			String a= trsDataDao.getPhoneType(cus);
			if(TrsDataConfig.TEL_SECRET_FLAG.equals(a)||"1".equals(a))
				cus.setTel("*"+cus.getTel());
		}
	}
	
	//客户编码处理
	public void dealCusCode(TrsModel cus)throws Exception{
		String addressCode=trsDataDao.getCusCode(cus);
		if(cus.getCustCode()==null)
			cus.setCustCode(addressCode);
		else if(addressCode!=null)
			cus.setCustCode(cus.getCustCode().concat("|").concat(addressCode));
		
		if(cus.getOrgShortPinyin()!=null&&cus.getCustCode()!=null){
			cus.setCustCode(cus.getCustCode().concat("|").concat(cus.getOrgShortPinyin()));
		}else if(cus.getCustCode()==null){
			cus.setCustCode(cus.getOrgShortPinyin());
		}
	}
	
}
